package com.pro.xwt.rest.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pro.xwt.common.model.BEmployee;
import com.pro.xwt.common.model.BToken;
import com.pro.xwt.common.service.BEmployeeService;
import com.pro.xwt.common.service.BTokenService;
import com.pro.xwt.common.utils.Common;
import com.pro.xwt.common.utils.DateFormatter;
import com.pro.xwt.common.utils.ThreeDESUtil;
import com.pro.xwt.rest.ResponseResult;

@Controller
@RequestMapping("/")
public class LoginController {
	@Autowired
	BEmployeeService bEmployeeService;
	@Autowired
	BTokenService tokenService;

	@RequestMapping(method = { RequestMethod.POST }, value = "login")
	@ResponseBody
	public ResponseResult login(@RequestBody BEmployee bEmployee, HttpServletRequest request,
			HttpServletResponse response) {
		List<BEmployee> be;
		if (bEmployee != null) {
			be = bEmployeeService.queryListByPojo(bEmployee);
			BToken bToken = new BToken();
			Map<String, Object> object = new HashMap<String, Object>();
			if (be.size() > 0) {
				String empId = be.get(0).getId();
				object.put("id", empId);
				object.put("role",  be.get(0).getRole());
				bToken.setUserId(empId);
				String token = generateToken(empId);
				bToken.setAuthToken(token);
				Date createTime = new Date();
				bToken.setCreateTime(createTime);
				bToken.setExpireTime(DateFormatter.getNextSeveralDay(createTime, 1));
				bToken.setIp(Common.toIpAddr(request));
				int flag = tokenService.insert(bToken);
				if (flag == 1) {
					object.put("authToken", token);
					return ResponseResult.success("用户登录成功", object);
				}
			}
			return ResponseResult.fail("帐号或密码错误",false);
		}
		return ResponseResult.fail("请输入帐号和密码",false);

	}

	private static String TAG = "LoginController";
	// 加密解密 秘钥 和门户之间
	private static final String SEED = "d$*16?.ghb#!&bke";
	// 分隔符
	public static final String SPLIT_CHAR = "|";

	/**
	 * 加密
	 * 
	 * @param appId
	 * @param appKey
	 * @param encodeType
	 * @return
	 */
	public static String generateToken(String userId) {
		long requestTimeStamp = System.currentTimeMillis();
		System.out.println(
				TAG + ": generateToken(userId:" + userId + ",generateTimeStamp:" + requestTimeStamp + ") start");
		String tokenStr = userId + SPLIT_CHAR + requestTimeStamp;
		String token = null;
		System.out.println(TAG + ": AES encode start");
		token = new ThreeDESUtil().getEncString(tokenStr, SEED);
		System.out.println(TAG + ": AES encode end");
		return token;
	}
}
